<script setup>
import * as Cesium from 'cesium';
import { ref, watch } from 'vue';

const map = ref(null);
const props = defineProps({
  viewer: {
    type: Object,
    default: null,
  },
});

// 使用 watch 监听 viewer 的变化
watch(
  () => props.viewer,
  (newViewer) => {
    if (newViewer) {
      map.value = newViewer;
    }
  },
  { immediate: true }
);

const changeMap = (type) => {
  if (!map.value) {
    console.error('MapTiles: Viewer 对象未初始化');
    return;
  }

  map.value.imageryLayers.removeAll();
  switch(type) {
    case 'OSM':
      map.value.imageryLayers.addImageryProvider(
        new Cesium.OpenStreetMapImageryProvider({
          url: 'https://a.tile.openstreetmap.org/'
        })
      );
      break;
    case 'TDT':
      map.value.imageryLayers.addImageryProvider(
        new Cesium.TiandituImageryProvider({
          url: 'http://t0.tianditu.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}',   // 天地图影像图层
          layer: 'vec_w',
          style: 'default',
          format: 'image/jpeg',
          tileMatrixSetID: 'c',
          maximumLevel: 18,
          credit: '天地图'
        })
      );
      break;
    case 'Google':
      map.value.imageryLayers.addImageryProvider(
        new Cesium.GoogleEarthImageryProvider({
          url: 'https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}'
        })
      );
      break;
    case 'clear':
      map.value.imageryLayers.removeAll();
      break;
    default:
      console.error('MapTiles: 未知底图类型:', type);
      break;
  }
};
</script>

<template>
  <el-dropdown placement="top-start">
    <el-button> 底图切换 </el-button>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="changeMap('OSM')">OSM底图</el-dropdown-item>
        <el-dropdown-item @click="changeMap('TDT')">天地图底图</el-dropdown-item>
        <el-dropdown-item @click="changeMap('Google')">谷歌底图</el-dropdown-item>
        <el-dropdown-item @click="changeMap('clear')">恢复默认</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<style scoped>
.el-button {
  background-color: #000;
  color: #4ADE80;
  border: 1px solid #4ADE80;
  border-radius: 4px;
}

.el-button:hover {
  background-color: #4ADE80;
  color: #000;
  border: 1px solid #4ADE80;
}
</style>
